package net.hiwii.db.bind.func;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;
import com.sleepycat.je.DatabaseException;

import net.hiwii.cognition.Expression;
import net.hiwii.db.ent.FunctionJudgment;
import net.hiwii.db.ent.StoredValue;
import net.hiwii.expr.FunctionExpression;
import net.hiwii.system.exception.ApplicationException;
import net.hiwii.system.util.EntityUtil;
import net.hiwii.system.util.StringUtil;
import net.hiwii.view.HObject;

public class FunctionExpressionBinding extends TupleBinding<FunctionExpression> {
	@Override
	public FunctionExpression entryToObject(TupleInput arg0) {
		try {
			FunctionExpression ret = new FunctionExpression();
			String type = arg0.readString();
//			boolean val = arg0.readBoolean();
//			ret.setPositive(val);
			int num = arg0.readInt();
			List<Expression> list = new ArrayList<Expression>();
			for(int n=0;n<num;n++){
				type = arg0.readString();
				String value = arg0.readString();
				Expression expr = StringUtil.parseString(value);
				list.add(expr);
			}
			ret.setArguments(list);
			return ret;
		} catch (IndexOutOfBoundsException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DatabaseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void objectToEntry(FunctionExpression arg0, TupleOutput arg1) {
		try {
//			arg1.writeBoolean(arg0.isPositive());
			arg1.writeInt(arg0.getArguments().size());
			for(int i=0;i<arg0.getArguments().size();i++) {
				StoredValue sv = EntityUtil.entityToRecord(arg0.getArguments().get(i));
				arg1.writeString(sv.getType());
				arg1.writeString(sv.getValue());
			}
		} catch (ApplicationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
